﻿using Dal;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bll
{
    public class MenuBll
    {
        public IList<Menu> GetAll()
        {
            using (var db = new BabyfaceEntities())
            {
                var dal = new MenuDal(db);
                var list = dal.GetAll();
                return list;
            }
        }

        public IList<Menu> GetMenuByRoleId(int RoleId)
        {
            if (RoleId == 0)
                return null;
            DataSet dataSet;
            using (var db = new BabyfaceEntities())
            {
                var dal = new MenuDal(db);
                dataSet = dal.GetMenuByRoleId(RoleId);
            }
            if (dataSet != null &&
                dataSet.Tables.Count > 0 &&
                dataSet.Tables[0].Rows.Count > 0)
            {
                IList<Menu> result = DataTableToListMenu(dataSet.Tables[0]);
                return result;
            }
            else
            {
                return null;
            }
        }
        public Menu DataRowToMenu(DataRow row)
        {
            var model = new Menu();
            if (row != null)
            {
                if (row["MenuId"] != null && row["MenuId"].ToString() != "")
                {
                    model.MenuId = int.Parse(row["MenuId"].ToString());
                }
                if (row["PId"] != null && row["PId"].ToString() != "")
                {
                    model.PId = int.Parse(row["PId"].ToString());
                }
                if (row["MenuName"] != null)
                {
                    model.MenuName = row["MenuName"].ToString();
                }
                if (row["MenuPath"] != null)
                {
                    model.MenuPath = row["MenuPath"].ToString();
                }
            }
            return model;
        }
        public IList<Menu> DataTableToListMenu(DataTable dt)
        {
            var modelList = new List<Menu>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                Menu model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = DataRowToMenu(dt.Rows[n]);
                    if (model != null)
                    {
                        modelList.Add(model);
                    }
                }
            }
            return modelList;
        }
    }
}
